<?php

namespace app\admin\controller\shopro\commission;

use addons\shopro\service\user\User;
use app\admin\controller\shopro\Common;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Performance;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\shopro\commission\Level as LevelModel;
use addons\shopro\service\commission\Agent as AgentService;
use fast\Tree;
use think\Db;
use think\db\Expression;

class Agent extends Common
{
    protected $noNeedRight = ['select'];

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new AgentModel();
    }

    /**
     * 查看
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }
        //$configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
        $list = $this->model->sheepFilter()->with(['user.parent_user', 'level_info', 'level_status_info', 'upgrade_level'])->paginate($this->request->param('list_rows', 10));
        /*$user_ids=UserModel::where(["parent_user_id"=>0])->column("id");
        $performance_sum=["last_market"=>0,"market"=>0];
        if(!empty($user_ids)){
            $performance = Performance::field("sum(money) money")
                ->whereTime("createtime","last month")
                ->whereIn("user_id",$user_ids)
                //->where("level >=".$configs["level"])
                ->group("user_id")
                ->select();//所有
            $performance_all = Performance::field("sum(money) money")
                ->whereTime("createtime","month")
                ->whereIn("user_id",$user_ids)
                //->where("level >=".$configs["level"])
                ->group("user_id")
                ->select();//所有
            if(!empty($performance)){
                $score=array_column($performance, 'money');
                $max=max($score);
                $sum=array_sum($score);
                $market=bcsub($sum,$max,2);
            }
            $performance_sum=[
                //"last_big_market"=>$big_market,
                "last_market"=>$market??0,
            ];
            if(!empty($performance_all)){
                $score=array_column($performance_all, 'money');
                $max=max($score);
                $sum=array_sum($score);
                $market=bcsub($sum,$max,2);
            }
            //$performance_sum["big_market"]=$big_market;
            $performance_sum["market"]=$market??0;
        }*/
        $performance_sum = ["last_market" => 0, "market" => 0];
        if (!empty($list)) {
            $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
            foreach ($list as $v) {
                if($v["level_info"]["level"]>=$configs["level"]){
                    /*$performance = Performance::field("sum(money) money")
                        ->whereTime("createtime", "last month")
                        ->where("level >=" . $configs["level"]." and user_id = ".$v["user_id"])
                        ->group("user_id")
                        ->select();//所有
                    $performance_all = Performance::field("sum(money) money")
                        ->whereTime("createtime", "month")
                        ->where("level >=" . $configs["level"]." and user_id = ".$v["user_id"])
                        ->group("user_id")
                        ->select();//所有*/
                    //$where_dividend["is_dividend"]=["=",1];
                    $where_dividend["is_self"]=["=",0];
                    $ids = Performance::whereTime("createtime", "last month")
                        ->where(["user_id"=>$v["user_id"]])
                        ->where($where_dividend)->column("order_id");
                    $parent_user_id=\app\common\model\User::where("parent_user_id",$v["user_id"])->column("id");
                    $performance = Performance::whereIn("user_id",$parent_user_id)
                        ->field("sum(money) money,user_id")
                        ->whereTime("createtime", "last month")
                        ->whereIn("order_id",$ids)
                        ->group("user_id")
                        ->select();
                    if (!empty($performance)) {
                        $score = array_column($performance, 'money');
                        $max = max($score);
                        $sum = array_sum($score);
                        $market = bcsub($sum, $max, 2);
                    }
                    $performance_sum = [
                        "last_market" => $market ?? 0,
                    ];
                    $ids = Performance::whereTime("createtime", "month")
                        ->where(["user_id"=>$v["user_id"]])
                        ->where($where_dividend)->column("order_id");
                    $performance_all = Performance::whereIn("user_id",$parent_user_id)
                        ->field("sum(money) money,user_id")
                        ->whereTime("createtime", "month")
                        ->whereIn("order_id",$ids)
                        ->group("user_id")
                        ->select();
                    if (!empty($performance_all)) {
                        $score = array_column($performance_all, 'money');
                        $max = max($score);
                        $sum = array_sum($score);
                        $market = bcsub($sum, $max, 2);
                    }
                    $performance_sum["market"] = $market ?? 0;
                }
                $v["performance_sum"] = $performance_sum;
            }
        }
        $this->success('分销商列表', null, ["list" => $list, "performance_sum" => $performance_sum]);
    }

    /**
     * 详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $detail = $this->model->with(['user.parent_user', 'level_info', 'level_status_info', 'upgrade_level'])->where('user_id', $id)->find();
        if (!$detail) {
            $this->error(__('No Results were found'));
        }

        $this->success('分销商详情', null, $detail);
    }


    /**
     * 团队
     *
     * @param  $id
     */
    public function team($id, $type = 0)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $detail = $this->model->with(['user.parent_user', 'level_info'])
            ->where('user_id', $id)
            ->find();
        if (!$detail) {
            $this->error(__('No Results were found'));
        }

        if (!empty($type)) {
            $ids = User::getParent($id);
            $agent_team = [];
            if (!empty($ids) && count($ids) > 1) {
                unset($ids[0]);
                $ids = implode(',', $ids);
                $exp = new Expression("field(user_id,$ids)");
                $agent_team = AgentModel::with(['user', 'level_info'])->whereIn("user_id", $ids)
                    ->order($exp)->select();
            }
            $detail->agent_team = $agent_team;
        } else {
            $detail->agent_team = AgentModel::hasWhere('user', function ($query) use ($detail) {
                return $query->where('parent_user_id', $detail->user_id);
            })->with(['user', 'level_info'])->select();
            $performance = Performance::field("sum(money) money")
                ->whereTime("createtime", "last month")
                ->where(["user_id" => $id])
                ->group("user_id")
                ->select();//所有
            $performance_all = Performance::field("sum(money) money")
                ->whereTime("createtime", "month")
                ->where(["user_id" => $id])
                ->group("user_id")
                ->select();//所有
            if (!empty($performance)) {
                $score = array_column($performance, 'money');
                $max = max($score);
                $sum = array_sum($score);
                $market = bcsub($sum, $max, 2);
            }
            $performance_sum = [
                "last_market" => $market ?? 0,
            ];
            if (!empty($performance_all)) {
                $score = array_column($performance_all, 'money');
                $max = max($score);
                $sum = array_sum($score);
                $market = bcsub($sum, $max, 2);
            }
            $performance_sum["market"] = $market ?? 0;
            $detail["performance_sum"] = $performance_sum;
        }
        $this->success('分销商详情', null, $detail);
    }

    // 选择分销商
    public function select()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->with(['user', 'level_info', 'level_status_info', 'upgrade_level'])
            ->paginate($this->request->param('list_rows', 10));

        $this->success('选择分销商', null, $data);
    }

    /**
     * 编辑
     *
     * @param  $id
     */
    public function edit($id = null)
    {
        $params = $this->request->only(['status', 'upgrade_lock', 'level_status', 'level', 'apply_info']);

        $result = Db::transaction(function () use ($id, $params) {
            $row = $this->model->with(['user', 'level_info', 'level_status_info', 'upgrade_level'])->where('user_id', $id)->find();
            if (!$row) {
                $this->error('未找到该分销商');
            }

            foreach ($params as $field => $value) {
                switch ($field) {
                    case 'status':  // 修改状态
                        return $this->changeStatus($row, $value);
                        break;
                    case 'level_status':    // 审核等级
                        return $this->changeLevelStatus($row, $value);
                        break;
                    case 'level':           // 修改等级
                        return $this->changeLevel($row, $value);
                        break;
                    default:
                        return $row->save([$field => $value]);
                }
            }
        });
        if ($result) {
            $this->success('更新成功', null, $result);
        } else {
            $this->error('更新失败');
        }
    }


    // 修改状态
    private function changeStatus($row, $value)
    {
        $result = $row->save(['status' => $value]);
        if ($result) {
            LogModel::add($row->user_id, 'agent', ['type' => 'status', 'value' => $value]);
            (new AgentService($row->user_id))->createAsyncAgentUpgrade();
        }
        return $result;
    }

    // 审核等级
    private function changeLevelStatus($row, $value)
    {
        if ($row->level_status == 0 && $value > 0) {
            $this->error('非法操作');
        }

        if ($value == 0) {  // 拒绝操作
            return $row->save(['level_status' => 0]);
        } else {            // 同意操作
            if ($row->upgrade_level) {
                $result = $row->save(['level_status' => 0, 'level' => $row->upgrade_level->level]);
                if ($result) {
                    LogModel::add($row->user_id, 'agent', ['type' => 'level', 'level' => $row->upgrade_level]);
                    (new AgentService($row->user_id))->createAsyncAgentUpgrade();
                }
                return $result;
            }
        }
        return false;
    }

    // 修改等级
    private function changeLevel($row, $value)
    {
        $level = LevelModel::find($value);
        if ($level) {
            $result = $row->save(['level' => $level->level]);
            if ($result) {
                LogModel::add($row->user_id, 'agent', ['type' => 'level', 'level' => $level]);
                (new AgentService($row->user_id))->createAsyncAgentUpgrade();
            }
            return $result;
        } else {
            $this->error('未找到该等级');
        }
    }

    // 更换推荐人
    public function changeParentUser($id)
    {
        $userAgent = new AgentService($id);

        if (!$userAgent->user) {
            $this->error('未找到该用户');
        }

        $parentUserId = $this->request->param('parent_user_id', 0);

        // 更换推荐人检查
        if ($parentUserId != 0) {
            $parentAgent = new AgentService($parentUserId);
            if (!$parentAgent->isAgentAvaliable()) {
                $this->error('选中用户暂未成为分销商,不能成为推荐人');
            }
            if (!$this->checkChangeParentAgent($id, $parentUserId)) {
                $this->error('不能绑定该上级');
            }
            LogModel::add($parentUserId, 'share', ['user' => $userAgent->user]);

            if ($userAgent->isAgentAvaliable()) {
                LogModel::add($id, 'bind', ['user' => $parentAgent->user ?? NULL]);
            }
        }

        $lastParentUserId = $userAgent->user->parent_user_id;

        $userAgent->user->parent_user_id = $parentUserId;
        $userAgent->user->save();

        if ($lastParentUserId > 0) {
            $userAgent->createAsyncAgentUpgrade($lastParentUserId);
        }

        if ($parentUserId > 0) {
            $userAgent->createAsyncAgentUpgrade($parentUserId);
        }
        $this->success('绑定成功');
    }

    // 递归往上找推荐人，防止出现推荐循环
    private function checkChangeParentAgent($userId, $parentUserId)
    {
        if ($userId == $parentUserId) {

            $this->error('推荐人不能是本人');
        }
        if ($parentUserId == 0) {
            return true;
        }

        $parentAgent = UserModel::find($parentUserId);

        if ($parentAgent) {
            if ($parentAgent->parent_user_id == $userId) {
                $this->error("已选中分销商的上级团队中已存在该用户");
            }
            if ($parentAgent->parent_user_id == 0) {
                return true;
            } else {
                return $this->checkChangeParentAgent($userId, $parentAgent->parent_user_id);
            }
        }

        return false;
    }

    /**
     * 导出
     * */
    public function export()
    {
        $cellTitles = [
            // 订单表字段
            'user_id' => '代理ID',
            'user.nickname' => '代理昵称',
            'user.mobile' => '代理手机号',
            'level_info.name' => '等级',
            'total_consume' => '消费金额',
            'performance' => 'pv值',
            'total_consume_pv' => '业绩',
            'payment_goods' => '货款',
            'money' => '余额',
            'parent_user.id' => '上级ID',
            'parent_user.nickname' => '上级昵称',
            'parent_user.mobile' => '上级手机号',
            'child_user_count_1' => '一级用户人数',
            'last_market' => '上月小市场业绩',
            'market' => '本月小市场业绩',
            'createtime' => '创建时间',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->with(['user.parent_user', 'level_info', 'level_status_info', 'upgrade_level'])->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '代理列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];

        $result = $export->export($params, function ($pages) use (&$total_order_amount, &$total_pay_fee, &$total_real_pay_fee, &$total_discount_fee, &$total_score_amount, $total) {
            $datas =$this->model->sheepFilter()->with(['user.parent_user', 'level_info', 'level_status_info', 'upgrade_level'])
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $newDatas = [];
            foreach ($datas as &$item) {
                $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
                $performance_sum=[
                    "last_market"=>0,
                    "market"=>0,
                ];
                if($item["level_info"]["level"]>=$configs["level"]){
                    $where_dividend["is_self"]=["=",0];
                    $ids = Performance::whereTime("createtime", "last month")
                        ->where(["user_id"=>$item["user_id"]])
                        ->where($where_dividend)->column("order_id");
                    $parent_user_id=\app\common\model\User::where("parent_user_id",$item["user_id"])->column("id");
                    $performance = Performance::whereIn("user_id",$parent_user_id)
                        ->field("sum(money) money,user_id")
                        ->whereTime("createtime", "last month")
                        ->whereIn("order_id",$ids)
                        ->group("user_id")
                        ->select();
                    if (!empty($performance)) {
                        $score = array_column($performance, 'money');
                        $max = max($score);
                        $sum = array_sum($score);
                        $market = bcsub($sum, $max, 2);
                    }
                    $performance_sum = [
                        "last_market" => $market ?? 0,
                    ];
                    $ids = Performance::whereTime("createtime", "month")
                        ->where(["user_id"=>$item["user_id"]])
                        ->where($where_dividend)->column("order_id");
                    $performance_all = Performance::whereIn("user_id",$parent_user_id)
                        ->field("sum(money) money,user_id")
                        ->whereTime("createtime", "month")
                        ->whereIn("order_id",$ids)
                        ->group("user_id")
                        ->select();
                    if (!empty($performance_all)) {
                        $score = array_column($performance_all, 'money');
                        $max = max($score);
                        $sum = array_sum($score);
                        $market = bcsub($sum, $max, 2);
                    }
                    $performance_sum["market"] = $market ?? 0;
                }
                $data = [
                    // 订单表字段
                    'user_id' => $item['user_id'],
                    'user.nickname' =>$item["user"]["nickname"]??'',
                    'user.mobile' =>"@".$item["user"]["mobile"]??'',
                    'level_info.name' =>$item["level_info"]["name"]??'',
                    'total_consume' =>$item["user"]["total_consume"]??0,
                    'performance' =>$item["user"]["performance"]??0,
                    'total_consume_pv' =>$item["user"]["total_consume_pv"]??0,
                    'payment_goods' =>$item["user"]["payment_goods"]??0,
                    'money' =>$item["user"]["money"]??0,
                    'parent_user.id' =>$item["user"]["parent_user"]["id"]??'',
                    'parent_user.nickname' =>$item["user"]["parent_user"]["nickname"]??'',
                    'parent_user.mobile' =>$item["user"]["parent_user"]["mobile"]??'',
                    'child_user_count_1' =>$item["child_user_count_1"],
                    'last_market' =>$performance_sum["last_market"],
                    'market' =>$performance_sum["market"],
                    'createtime' =>$item["createtime"],
                ];
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
